//
//  SafeArray.swift
//  APSwift
//
//  Created by jianbo.pei on 2023/7/14.
//

import Foundation

/// A thread-safe array.
public class SafeArray<Element> {
    fileprivate let queue = DispatchQueue(label: "com.jianbo.pei.safe_array", attributes: .concurrent)
    fileprivate var array = [Element]()
}

public extension SafeArray {
    
    var first: Element? {
        var result: Element?
        queue.sync { result = self.array.first }
        return result
    }
    
    var last: Element? {
        var result: Element?
        queue.sync { result = self.array.last }
        return result
    }
    
    var count: Int {
        var result = 0
        queue.sync { result = self.array.count }
        return result
    }
}

// MARK: - 写操作
public extension SafeArray {
    
    func append( _ element: Element) {
        queue.async(flags: .barrier) {
            self.array.append(element)
        }
    }
}
